package person.wend.javalearnexample.util;
// 注意: 下面的代码是示意性的，因为 JDK 自身不提供版本1 UUID 的生成方法。
// 如果你需要生成版本1的UUID，请考虑使用第三方库，例如：

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class UUIDExample {
    public static void main(String[] args) {
        uuidVersion3Test();
        uuidVersion4Test();
        uuidVersion5Test();
    }

    public static void uuidVersion3Test() {
        // 定义命名空间（可以是任何有效的UUID）
        UUID namespaceUUID = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8");

        // 创建版本3的UUID
        byte[] nameBytes = "exampleName".getBytes(StandardCharsets.UTF_8);
        UUID version3UUID = UUID.nameUUIDFromBytes(nameBytes);
        System.out.println("Version 3 UUID (from 'exampleName'): " + version3UUID);

    }

    public static void uuidVersion4Test() {
        // 创建版本4的UUID
        UUID version4UUID = UUID.randomUUID();
        System.out.println("Version 4 UUID: " + version4UUID);
    }

    public static void uuidVersion5Test(){
        // 定义命名空间（可以是任何有效的UUID）
        UUID namespaceUUID = UUID.fromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8");

        // 创建版本5的UUID
        String name = "exampleName";
        try{
            UUID version5UUID = createUUIDv5(namespaceUUID, name);
            System.out.println("Version 5 UUID (from 'exampleName'): " + version5UUID);
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


    }

    private static UUID createUUIDv5(UUID namespace, String name) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update((namespace.toString() + name).getBytes());
        byte[] digest = md.digest();

        BigInteger hash = new BigInteger(1, digest);
        long msb = hash.shiftRight(64).longValue();
        long lsb = hash.longValue();

        // 设置版本号为5
        msb = (msb & 0xffffffffffff0fffL) | 0x0000000000005000L;
        // 设置变体位
        lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L;

        return new UUID(msb, lsb);
    }
}
